const BOOL_VALUE = ["true", "false"] as const;
const IS_NUMBER_REG = /^\d+$/;
const IS_ARRAY_REG = /'/g;

//@ts-ignore
export function parseEnv(env: Record<string, string>): ImportMetaEnv {
  const viteEnv = JSON.parse(JSON.stringify(env));
  for (const key in env) {
    if (BOOL_VALUE.includes(env[key] as (typeof BOOL_VALUE)[number])) {
      viteEnv[key] = env[key] === "true";
    }

    if (IS_NUMBER_REG.test(env[key])) {
      viteEnv[key] = Number(env[key]);
    }

    if (viteEnv[key] === "undefined") {
      viteEnv[key] = undefined;
    }

    if (viteEnv[key] === "null") {
      viteEnv[key] = null;
    }

    if (key === "VITE_PROXY") {
      viteEnv[key] = viteEnv[key].replace(IS_ARRAY_REG, '"');
      viteEnv[key] = JSON.parse(viteEnv[key]);
    }
  }
  return viteEnv;
}
